package com.vvlive.caibao.smartcity.fragment;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.vvlive.caibao.smartcity.base.BaseFragment;
import com.vvlive.caibao.smartcity.base.CalendarViews;
import com.vvlive.caibao.smartcity.base.GetDeptInfo;
import com.vvlive.caibao.smartcity.bean.Dept;
import com.vvlive.caibao.smartcity.bean.MeetingRoom;
import com.vvlive.caibao.smartcity.bean.NewMeetingInfo;
import com.vvlive.caibao.smartcity.callback.LoadDeptRoomCallBack;
import com.vvlive.caibao.smartcity.ui.OrderOneMeetingActivity;
import com.vvlive.caibao.smartcity.utils.DialogUtil;

import smartcity.vvlive.caibao.com.smartc.R;


/**
 * Created by zhj on 2015/9/7.
 * 所有会议
 */
public class PagerAllMeetingsFragment extends BaseFragment {

    public static final String NEW_MEETING_INFO_KEY = "new_meeting_info";

    public static final int ORDER_ONE_MEETING_REQUEST_CODE = 100;

    private static final int VIEW_DAY = 1;
    private static final int VIEW_WEEK = 2;
    private static final int VIEW_MONTH = 3;

    private static final String VIEW_DAY_TAG = "_day_";
    private static final String VIEW_WEEK_TAG = "_week_";
    private static final String VIEW_MONTH_TAG = "_month_";

    private static final int PREV = -1;
    private static final int NEXT = 1;

    private static final int CONTAINER_VIEW_ID = R.id.calendar_views_wrapper;

    private int viewType = VIEW_MONTH;
    private String viewTag = VIEW_MONTH_TAG;
    private String[] viewTags = {VIEW_DAY_TAG, VIEW_WEEK_TAG, VIEW_MONTH_TAG};

    private Listener mListener;

    private RadioButton mDay;
    private RadioButton mWeek;
    private RadioButton mMonth;

    private Button mPrev;
    private Button mNext;

    private TextView mHeaderText;
    private TextView mPickDept;
    private TextView mPickRoom;
    private ImageButton mRefreshButton;

    private String mDeptName, mDeptId;
    private String mRoomName, mRoomId;

    private GetDeptInfo mGetDeptInfo;
    /**
     * 预定会议
     */
    private Button mOrder;

    private RelativeLayout mViewsWrapper;
    private FragmentManager mManager;
    private FragmentTransaction mTransition;

    private static DayViewFragment mDayView;
    private static WeekViewFragment mWeekView;
    private static MonthViewFragment mMonthView;

    private LoadDeptRoomCallBack mLoadCallBack;

    @Override
    public int getContentRes() {
        return R.layout.pagerfragment_all_meetings;
    }

    @Override
    public void initFragment() {

        mListener = new Listener();
        mGetDeptInfo = new GetDeptInfo();

        mDay = findView(R.id.meetingview_day);
        mWeek = findView(R.id.meetingview_week);
        mMonth = findView(R.id.meetingview_month);

        mPrev = findView(R.id.meetingview_prev);
        mNext = findView(R.id.meetingview_next);

        mHeaderText = findView(R.id.calendar_header_text);
        mPickDept = findView(R.id.calendar_pick_dept);
        mPickRoom = findView(R.id.calendar_pick_room);

        mRefreshButton = findView(R.id.meetings_refresh);

        mOrder = findView(R.id.meetings_order);
        mViewsWrapper = findView(R.id.calendar_views_wrapper);

        mManager = getFragmentManager();
        resetCalendarView();

        mDay.setOnClickListener(mListener);
        mWeek.setOnClickListener(mListener);
        mMonth.setOnClickListener(mListener);
        mPrev.setOnClickListener(mListener);
        mNext.setOnClickListener(mListener);
        mOrder.setOnClickListener(mListener);
        mPickDept.setOnClickListener(mListener);
        mPickRoom.setOnClickListener(mListener);
        mRefreshButton.setOnClickListener(mListener);

        mLoadCallBack = new LoadDeptRoomCallBack();
        mLoadCallBack.setListener(new LoadListener());
        mGetDeptInfo.load(mLoadCallBack);

    }

    private String[] mDeptIds;
    private String[] mDeptNames;
    private String[] mRoomIds;
    private String[] mRoomNames;

    private class LoadListener implements LoadDeptRoomCallBack.OnLoadListener {

        @Override
        public void onLoadFinish() {
            mDeptIds = mLoadCallBack.getDeptIds();
            mDeptNames = mLoadCallBack.getDeptNames();

            mDeptId = mDeptIds[0];
            mDeptName = mDeptNames[0];

            mPickDept.setText(mDeptName);

            mRoomIds = mLoadCallBack.getRoomIdsByDeptId(mDeptId);
            mRoomNames = mLoadCallBack.getRoomBamesByDeptId(mDeptId);

            mRoomId = mRoomIds[0];
            mRoomName = mRoomNames[0];

            mPickRoom.setText(mRoomName);

//            ((CalendarViews) mManager.findFragmentByTag(viewTag)).onSelectRoom(new Dept(mDeptId, mDeptName),
//                    new MeetingRoom(mRoomId, mRoomName, mDeptId));

            for (String tag : viewTags) {
                CalendarViews view = (CalendarViews) mManager.findFragmentByTag(tag);
                if (view != null) {
                    view.onSelectRoom(
                            new Dept(mDeptId, mDeptName),
                            mLoadCallBack.getMeetingRoomsArrayByDeptId(mDeptId)
                    );
                }
            }

        }

        @Override
        public void onLoadFailed(int code, String msg) {

        }
    }

    private class Listener implements View.OnClickListener {

        private Intent mIntent;

        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.meetingview_day:
                    // 选择天视图
                    viewType = VIEW_DAY;
                    resetCalendarView();
                    break;
                case R.id.meetingview_week:
                    // 选择周视图
                    viewType = VIEW_WEEK;
                    resetCalendarView();
                    break;
                case R.id.meetingview_month:
                    // 选择月视图
                    viewType = VIEW_MONTH;
                    resetCalendarView();
                    break;

                case R.id.meetings_order:
                    // 预定会议
                    if (mIntent == null) {
                        mIntent = new Intent();
                    }
                    mIntent.setClass(getActivity(), OrderOneMeetingActivity.class);
                    Bundle data = new Bundle();
                    NewMeetingInfo newMeetingInfo = new NewMeetingInfo();
                    newMeetingInfo.setDept(new String[]{mDeptId, mDeptName});
                    newMeetingInfo.setRoom(new String[]{mRoomId, mRoomName});
                    newMeetingInfo.setStartTime(getCalendarViewByTag(viewTag).getDate().getTimeInMillis());
                    data.putSerializable(NEW_MEETING_INFO_KEY, newMeetingInfo);
                    mIntent.putExtras(data);
                    startActivityForResult(mIntent, ORDER_ONE_MEETING_REQUEST_CODE);
                    break;

                case R.id.meetingview_prev:
                    // 上一天（周，月）
                    prevOrNext(PREV);
                    break;
                case R.id.meetingview_next:
                    // 下一天（周，月）
                    prevOrNext(NEXT);
                    break;
                case R.id.calendar_pick_dept:
                    // 选择部门
                    pickDept();
                    break;
                case R.id.calendar_pick_room:
                    // 选择会议室
                    pickRoom();
                    break;
                case R.id.meetings_refresh:
                    rotate(v);
                    break;
            }
        }

    }

    private Animation mAnim;

    private void rotate(final View view) {
        if (mAnim == null) {
            mAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.refresh_rotate);
            mAnim.setInterpolator(new LinearInterpolator());
        }
        view.startAnimation(mAnim);
        CalendarViews calendarView = getCalendarViewByTag(viewTag);
        calendarView.onRefresh(mDataRefreshListener);
    }

    private CalendarViews getCalendarViewByTag(String viewTag) {
        return (CalendarViews) mManager.findFragmentByTag(viewTag);
    }

    private CalendarViews.OnRefreshListener mDataRefreshListener = new CalendarViews.OnRefreshListener() {
        @Override
        public void onFinish(int tag) {
            if (CalendarViews.REFRESH_SUCCESS == tag) {
                toast("刷新成功");
            } else if (CalendarViews.REFRESH_FAILURE == tag) {
                toast("刷新失败，请重试");
            }
            mRefreshButton.clearAnimation();
        }
    };

    /**
     * 选择机构（部门）
     */
    private void pickDept() {
        DialogUtil.showItemsDialog(getActivity(), "请选择机构",
                mDeptNames, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        mDeptId = mDeptIds[which];
                        mDeptName = mDeptNames[which];

                        mPickDept.setText(mDeptName);

                        mRoomNames = mLoadCallBack.getRoomBamesByDeptId(mDeptId);
                        mRoomIds = mLoadCallBack.getRoomIdsByDeptId(mDeptId);

                        mRoomId = mRoomIds[0];
                        mRoomName = mRoomNames[0];
                        mPickRoom.setText(mRoomName);

                        getCalendarViewByTag(viewTag).onSelectRoom(
                                new Dept(mDeptId, mDeptName),
                                mLoadCallBack.getMeetingRoomsArrayByDeptId(mDeptId)
                        );

                    }
                });
    }

    /**
     * 选择会议室
     */
    private void pickRoom() {
        DialogUtil.showItemsDialog(getActivity(), mRoomNames[0],
                mRoomNames, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        mRoomId = mRoomIds[which];
                        mRoomName = mRoomNames[which];
                        mPickRoom.setText(mRoomName);

                        getCalendarViewByTag(viewTag).onSelectRoom(
                                new Dept(mDeptId, mDeptName),
                                new MeetingRoom[]{
                                        mLoadCallBack.getMeetingRoomsArrayByDeptId(mDeptId)[which]
                                }
                        );

                    }
                });
    }

    private void prevOrNext(int option) {

        CalendarViews calendarView = getCalendarViewByTag(viewTag);
        if (option == PREV) {
            calendarView.prev();
        } else if (option == NEXT) {
            calendarView.next();
        }

        mHeaderText.setText(calendarView.getHeaderText());

    }

    /**
     * 重置日历视图
     */
    private void resetCalendarView() {
        mTransition = mManager.beginTransaction();
        Fragment dayFragment = mManager.findFragmentByTag(VIEW_DAY_TAG);
        Fragment weekFragment = mManager.findFragmentByTag(VIEW_WEEK_TAG);
        Fragment monthFragment = mManager.findFragmentByTag(VIEW_MONTH_TAG);
        if (dayFragment != null) {
            mTransition.hide(dayFragment);
        }
        if (weekFragment != null) {
            mTransition.hide(weekFragment);
        }
        if (monthFragment != null) {
            mTransition.hide(monthFragment);
        }
        switch (viewType) {
            case VIEW_DAY:
                if (dayFragment == null) {
                    mDayView = new DayViewFragment();
                    mTransition.add(CONTAINER_VIEW_ID, mDayView, VIEW_DAY_TAG);
                } else {
                    mTransition.show(mDayView);
                }
                viewTag = VIEW_DAY_TAG;
                mHeaderText.setText(mDayView.getHeaderText());
                break;
            case VIEW_WEEK:
                if (weekFragment == null) {
                    mWeekView = WeekViewFragment.getInstance(null);
                    mTransition.add(CONTAINER_VIEW_ID, mWeekView, VIEW_WEEK_TAG);
                } else {
                    mTransition.show(mWeekView);
                }
                viewTag = VIEW_WEEK_TAG;
                mHeaderText.setText(mWeekView.getHeaderText());
                break;
            case VIEW_MONTH:
                if (monthFragment == null) {
                    mMonthView = new MonthViewFragment();
                    mTransition.add(CONTAINER_VIEW_ID, mMonthView, VIEW_MONTH_TAG);
                } else {
                    mTransition.show(mMonthView);
                }
                viewTag = VIEW_MONTH_TAG;
                mHeaderText.setText(mMonthView.getHeaderText());
                break;
        }
        mTransition.commit();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ORDER_ONE_MEETING_REQUEST_CODE) {

            if (resultCode == OrderOneMeetingActivity.ORDER_RESULT_CODE) {
                for (String viewTag : viewTags) {
                    CalendarViews view = (CalendarViews) mManager.findFragmentByTag(viewTag);
                    if (view != null) {
                        view.onResult(requestCode, resultCode, data);
                    }
                }
            }

        }

    }

}
